import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import AppLayout from '@/layout/AppLayout.vue'
import RuleCenterRouter from './modules/ruleCenter'
import { getToken } from '@/utils/token'

const routes: RouteRecordRaw[] = [
	{
		path: '/',
		component: AppLayout,
		children: [
			{
				path: '/', // 默认子路由
				name: 'home',
				component: () => import('../views/RuleCenter/index.vue'),
			},
			RuleCenterRouter,
			{
				path: 'yudao',
				name: 'yuDao',
				component: () => import('../views/yuDao/index.vue'),
				meta: {
					title: '芋道子应用',
				},
			},
			{
				path: 'bisheng',
				name: 'biSheng',
				component: () => import('../views/bisheng/index.vue'),
				meta: {
					title: '毕昇-会话',
				},
			},
			{
				path: 'bisheng/sys',
				name: 'biShengSys',
				component: () => import('../views/bisheng/sys/index.vue'),
				meta: {
					title: '毕昇-系统',
				},
			},
		],
	},
	{
		path: '/login',
		name: 'login',
		component: () => import('@/views/Login/index.vue'),
	},
]

const router = createRouter({
	history: createWebHashHistory(), // 路由模式
	routes, // 路由规则
})

// 全局前置守卫
router.beforeEach((to: any, form: any, next: any) => {
	nprogress.start() // 开始加载进度条

	const token = getToken()

	if (token) {
		if (to.path === '/login') {
			next('/')
		} else {
			next()
		}
	} else {
		if (to.path == '/login') {
			next()
		} else {
			next({ path: '/login' })
		}
	}
})

// 全局后置守卫
router.afterEach(() => {
	nprogress.done() // 结束进度条
})

export default router
